<?php
/**
 *
 * User: Traun
 * Date: 2021/8/21
 * Time: 10:53
 * @copyright Copyright (c) 湖南悦奥网络技术有限公司 .
 */

class Db
{
    private $config = [
        'db' => 'mysql',
        'host' => '127.0.0.1',
        'port'  =>  '3306',
        'dbname'    =>  'mvc',
        'username'  =>  'mvc',
        'password'  =>  'Lf7hyCcykH4TdcjN',
        'charset'   =>  'utf8',
    ];
    private static $instance = null;
    /**
     * @var PDO 数据库对象
     */
    private $conn = null;
    /**
     * @var string 数据库插入成功后返回的id
     */
    public $insertId;
    /**
     * @var false|int 数据库更新影响的行数
     */
    public $num;


    private function __construct($params)
    {
        $this->config = array_merge($this->config,$params);
        self::connect();
    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    public static function getInstance($params = []){
        if (!self::$instance instanceof self){
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    /**
     * 连接数据库
     * User: traun
     * Date: 2021/8/21
     * Time: 11:19
     * @param
     */
    private function connect(){
        try {
            // 配置数据源
            $dsn="{$this->config['db']}:host={$this->config['host']};dbname={$this->config['dbname']}";
            $this->conn =  new PDO($dsn,$this->config['username'],$this->config['password']);
        } catch (Exception $e) {
            die('数据库连接失败'.$e->getMessage());
        }
    }

    /**
     * 数据库插入和更新操作
     * User: traun
     * Date: 2021/8/21
     * Time: 11:27
     * @param
     */
    public function exec($sql=''){
        empty($sql) && die('sql语句不能为空');
        $res = $this->conn->exec($sql);
        if ($res > 0) {
            //操作成功判断是插入还是更新
            if (!empty($this->conn->lastInsertId())){
                $this->insertId = $this->conn->lastInsertId();
            }
            $this->num = $res;
        } else {
            // 插入失败返回错误信息
            $error = $this->conn->errorInfo();
            print '数据库操作失败！'.'错误标识符：'.$error[0].'错误代码：'.$error[1].'错误信息：'.$error[2];
        }
    }

    /**
     * 获取单条查询结果
     * User: traun
     * Date: 2021/8/21
     * Time: 11:29
     * @param
     * @return mixed
     */
    public function fetch($sql){
        return $this->conn->query($sql)->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * 获取多条数据
     * User: traun
     * Date: 2021/8/21
     * Time: 11:30
     * @param
     * @return array
     */
    public function fetchAll($sql){
        return $this->conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }
}